package com.icloud.system.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icloud.common.database.mapper.SysSettingsMapper;
import com.icloud.common.database.model.SysSettings;
import com.icloud.common.core.api.ResultCode;
import com.icloud.common.web.exception.Asserts;
import com.icloud.common.web.util.AuthUtil;
import com.icloud.system.boot.dto.SysSettingsUpdateDto;
import com.icloud.system.boot.service.SysSettingsService;
import com.icloud.system.boot.vo.SysSettingsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 系统设置service 实现类
 */
@Service
public class SysSettingsServiceImpl extends ServiceImpl<SysSettingsMapper, SysSettings> implements SysSettingsService {
    @Autowired
    private AuthUtil authUtil;
    @Override
    public SysSettingsVo get() {
        LambdaQueryWrapper<SysSettings> query = new LambdaQueryWrapper<>();
        SysSettings sysSettings = baseMapper.selectOne(query);
        SysSettingsVo vo = new SysSettingsVo();
        if(sysSettings==null){
            return vo;
        }
        BeanUtils.copyProperties(sysSettings, vo);
        return vo;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean update(SysSettingsUpdateDto dto) {
        Long settingId = dto.getId();
        SysSettings sysSettings = baseMapper.selectById(settingId);
        Asserts.fail(null==sysSettings, ResultCode.DATA_NOT_EXISTS);

        Long loginId = authUtil.getUserId();

        SysSettings updated = new SysSettings();
        BeanUtils.copyProperties(dto, updated);
        updated.setId(settingId);
        updated.setUpdatedId(loginId);
        int effect = baseMapper.updateById(updated);
        return effect>0;
    }
}
